package com.mvc.framework.handler;

import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.framework.servlet.MyModelAndView;

public class HandlerAdapter {

	private Map<String, Integer> paramMapping;

	public HandlerAdapter(Map<String, Integer> paramMapping) {
		this.paramMapping = paramMapping;
	}

	public Map<String, Integer> getParamMapping() {
		return paramMapping;
	}

	public void setParamMapping(Map<String, Integer> paramMapping) {
		this.paramMapping = paramMapping;
	}

	public MyModelAndView handle(HttpServletRequest request, HttpServletResponse response, Handler handler) throws Exception {
		Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
		// 存储参数
		Object[] paramValues = new Object[parameterTypes.length];

		// 请求中获取所有参数
		@SuppressWarnings("unchecked")
		Map<String, String[]> parameterMap = request.getParameterMap();
		Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
		for (Entry<String, String[]> entry : entrySet) {
			String key = entry.getKey();

			System.out.println("key==========" + key);
			System.out.println("value========" + Arrays.toString(entry.getValue()));
			String value = Arrays.toString(entry.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");
			System.out.println(value);

			if (!paramMapping.containsKey(key)) {
				continue;
			}

			int index = paramMapping.get(key);
			paramValues[index] = castStringValue(value, parameterTypes[index]);

		}

		//
		String reqName = HttpServletRequest.class.getName();
		if (paramMapping.containsKey(reqName)) {
			int reqIndex = paramMapping.get(reqName);
			paramValues[reqIndex] = request;
		}

		String resqName = HttpServletResponse.class.getName();
		if (paramMapping.containsKey(resqName)) {
			int resqIndex = paramMapping.get(resqName);
			paramValues[resqIndex] = response;
		}

		System.out.println("paramValues==========" + Arrays.toString(paramValues));
		boolean isModelAndView = handler.getMethod().getReturnType() == MyModelAndView.class;
		Object result = handler.getMethod().invoke(handler.getController(), paramValues);
		if (isModelAndView) {
			return (MyModelAndView) result;
		} else {
			return null;
		}

	}

	private Object castStringValue(String value, Class<?> clazz) {
		if (clazz == String.class) {
			return value;
		} else if (clazz == Integer.class) {
			return Integer.valueOf(value);
		} else if (clazz == int.class) {
			return Integer.valueOf(value).intValue();
		} else {
			return null;
		}
	}

	@Override
	public String toString() {
		return "HandlerAdapter [paramMapping=" + paramMapping + "]";
	}

}
